<!-- wangeditor富文本编辑器 -->
<template>
  <div class="my-wangeditor-component">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <div class="wangeditor-Form">
      <div class="title-container">
        <input
          class="pagetitle"
          v-model.trim="ruleForm.title"
          placeholder="Page title..."
          autofocus
        />
      </div>
      <div class="editor-middle">
        <Editor
          v-model="valueHtml"
          style="height: 800px; overflow-y: hidden"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
        />
      </div>
    </div>
  </div>
</template>
<script>
import request from "utils/request";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import {
  onBeforeUnmount,
  ref,
  shallowRef,
  onMounted,
  watch,
  reactive,
} from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { ElMessage, ElLoading } from "element-plus";
import { useRoute } from "vue-router";

export default {
  name: "MyWangeditor",
  components: { Editor, Toolbar },
  setup(props, { emit }) {
    const route = useRoute();
    const id = ref(route.query.id);
    const ruleFormRef = ref();
    const ruleForm = reactive({
      title: "",
    });
    const rules = reactive({
      title: [{ required: true, trigger: "blur" }],
    });

    const submitForm = async () => {
      if (!ruleForm.title || !valueHtml.value) {
        ElMessage({
          type: "error",
          message: "数据信息不全，请完善！",
          showClose: true,
          duration: 1000,
        });
        return false;
      }
      let ret = null;
      if (id.value) {
        ret = await request.patch(`/essay/${id.value}`, {
          essaytitle: ruleForm.title,
          content: editorRef.value.getHtml(),
        });
      } else {
        ret = await request.post("/essay/add", {
          essaytitle: ruleForm.title,
          content: editorRef.value.getHtml(),
        });
      }

      if (ret.code == 200) {
        ElMessage({
          type: "success",
          message: "success",
          showClose: true,
          duration: 1000,
        });
        id.value = ret.data;
      } else {
        ElMessage({
          type: "error",
          message: "添加失败",
          showClose: true,
          duration: 1000,
        });
      }
    };

    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();
    // 内容 HTML
    const valueHtml = ref("<p><br></p>");
    emit("valueHtml", valueHtml);
    // 模拟 ajax 异步获取内容
    onMounted(async () => {
      if (id.value) {
        let ret = await request.get(`/essay/${id.value}`);
        if (ret.code == 200) {
          ruleForm.title = ret.data.essaytitle;
          valueHtml.value = ret.data.content;
        }
      }
    });

    function init(data) {
      valueHtml.value = data;
    }
    watch(valueHtml, (val) => {
      emit("BoxValue", val);
    });
    const toolbarConfig = {
      //删除工具栏中不需要的选项比如视频就是group-video
      excludeKeys: [
        "group-video",
        "full-screen",
        "emotion",
      ],
    };

    const uploadImg = async (file, insertFn) => {
      const loading = ElLoading.service({
        lock: true,
        text: "资源较大，请耐心等待......",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const imgData = new FormData(); // 创建form对象
      imgData.append("file", file); // 通过append向form对象添加数据
      imgData.append("namespace", "note");
      const config = {
        headers: { "Content-Type": "multipart/form-data" },
      };
      let ret = await request.upload("/upload", imgData, config);
      loading.close();
      if (ret.code == 200) {
        insertFn(ret.data);
      } else {
        ElMessage({
          type: "error",
          message: "上传失败",
          showClose: true,
          duration: 1000,
        });
      }
    };

    const editorConfig = {
      placeholder: "请输入内容...",
      // 所有的菜单配置，都要在 MENU_CONF 属性下
      MENU_CONF: {
        //配置上传图片
        uploadImage: {
          customUpload: uploadImg,
        },
      },
    };

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });

    const handleCreated = (editor) => {
      editorRef.value = editor; // 记录 editor 实例，重要！
    };

    return {
      editorRef,
      valueHtml,
      mode: "default", // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      init,
      ruleFormRef,
      ruleForm,
      rules,
      submitForm,
    };
  },
};
</script>

<style lang="scss">


.wangeditor-Form {
  width: 1000px;
  margin: 0 auto;
  background: #f8f8f8;
  height: calc(100vh - 100px);
  overflow-y: auto;
  .title-container {
    padding: 20px 0;
    border-bottom: 1px solid #e8e8e8;
    background: white;
    .pagetitle {
      font-size: 30px;
      border: 0;
      outline: none;
      width: 100%;
      line-height: 1;
    }
  }
  .editor-middle {
    min-height: 800px;
    background: white;
   ::v-deep &>div{
      min-height: 800px !important;
    }
  }
}
.my-wangeditor-component {
  background: #f8f8f8;
}

.editor-content-view {
  border: 3px solid #ccc;
  border-radius: 5px;
  padding: 0 10px;
  margin-top: 20px;
  overflow-x: auto;
}

.editor-content-view p,
.editor-content-view li {
  white-space: pre-wrap; /* 保留空格 */
}

.editor-content-view blockquote {
  border-left: 8px solid #d0e5f2;
  padding: 10px 10px;
  margin: 10px 0;
  background-color: #f1f1f1;
}

.editor-content-view code {
  font-family: monospace;
  background-color: #eee;
  padding: 3px;
  border-radius: 3px;
}
.editor-content-view pre > code {
  display: block;
  padding: 10px;
}

.editor-content-view table {
  border-collapse: collapse;
}
.editor-content-view td,
.editor-content-view th {
  border: 1px solid #ccc;
  min-width: 50px;
  height: 20px;
}
.editor-content-view th {
  background-color: #f1f1f1;
}

.editor-content-view ul,
.editor-content-view ol {
  padding-left: 20px;
}

.editor-content-view input[type="checkbox"] {
  margin-right: 5px;
}
button[data-menu-key='fullScreen']{
  display: none;
}
</style>
